package com.dnjn.happiness.survey.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dnjn.happiness.common.core.utils.StringUtils;
import com.dnjn.happiness.survey.domain.Answer;
import com.dnjn.happiness.survey.domain.Question;
import com.dnjn.happiness.survey.domain.Survey;
import com.dnjn.happiness.survey.domain.SurveyRecord;
import com.dnjn.happiness.survey.domain.Tiku;
import com.dnjn.happiness.survey.mapper.QuestionMapper;
import com.dnjn.happiness.survey.mapper.TikuMapper;
import com.dnjn.happiness.survey.service.IAnswerService;
import com.dnjn.happiness.survey.service.IQuestionService;
import com.dnjn.happiness.survey.service.ISurveyRecordService;
import com.dnjn.happiness.survey.service.ISurveyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Amber
 * @since 2023-10-04
 */
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements IQuestionService {

    @Autowired
    private TikuMapper tikuMapper;

    @Autowired
    private IAnswerService answerService;

    @Autowired
    private ISurveyRecordService surveyRecordService;

    @Autowired
    private ISurveyService surveyService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addQuestion(Survey domian) {
        //传进来timuid 查询提库里边的题目
        List<Long> timuIds = domian.getTimuIds();
        //
        //遍历传进来的timuids
        if (timuIds != null && !timuIds.isEmpty()) {
            timuIds.stream().forEach(timuid -> {
                QueryWrapper<Tiku> wrapper = new QueryWrapper<>();
                wrapper.eq("tiku_id", timuid);
                List<Tiku> tikus = tikuMapper.selectList(wrapper);
                tikus.stream().forEach(t -> {
                    Question question = new Question();
                    question.setIsSelectPack(t.getIsSelectPack());
                    question.setScoreOptionA(t.getScoreOptionA());
                    question.setScoreOptionB(t.getScoreOptionB());
                    question.setScoreOptionC(t.getScoreOptionC());
                    question.setScoreOptionD(t.getScoreOptionD());
                    question.setScoreOptionE(t.getScoreOptionE());
                    question.setScoreOptionF(t.getScoreOptionF());
                    question.setScoreOptionG(t.getScoreOptionG());
                    question.setOptionA(t.getOptionA());
                    question.setOptionB(t.getOptionB());
                    question.setOptionC(t.getOptionC());
                    question.setOptionD(t.getOptionD());
                    question.setOptionE(t.getOptionE());
                    question.setOptionF(t.getOptionF());
                    question.setOptionG(t.getOptionG());
                    question.setIsMultipleChoice(t.getIsMultipleChoice());
                    question.setAnswer(t.getAnswer());
                    question.setSurveyId(domian.getSurveyId());
                    question.setSiteId(domian.getSiteId());
                    question.setTitle(t.getTitle());
                    question.setTikuId(timuid);
                    question.setAnswerScoreType(t.getAnswerScoreType());
                    question.setWordScoreOptionA(t.getWordScoreOptionA());
                    question.setWordScoreOptionB(t.getWordScoreOptionB());
                    question.setWordScoreOptionC(t.getWordScoreOptionC());
                    question.setWordScoreOptionD(t.getWordScoreOptionD());
                    question.setWordScoreOptionE(t.getWordScoreOptionE());
                    question.setWordScoreOptionF(t.getWordScoreOptionF());
                    question.setWordScoreOptionG(t.getWordScoreOptionG());
                    baseMapper.insert(question);
                });
            });
        } else {
            return 0;
        }

        return 1;

    }

    @Override
    public List<Question> querySurveyBySurveyId(Question domain) {

        return baseMapper.querySurveyBySurveyId(domain);

    }

    @Override
    public List<Question> selectBysurveyId(Long surveyId) {
        QueryWrapper<Question> wrapper = new QueryWrapper<>();
        wrapper.eq("survey_id", surveyId);
        List<Question> questions = baseMapper.selectList(wrapper);
        return questions;
    }

    @Override
    public List<Question> queryAnswerByQuestionId(Long questionId) {

        QueryWrapper<Question> wrapper = new QueryWrapper<>();
        wrapper.eq("question_id", questionId);
        List<Question> questions = baseMapper.selectList(wrapper);
        return questions;
    }

    @Override
    public List<Question> querySurveyQuestionBySurveyId(Long surveyId, Long userId) {
        return baseMapper.querySurveyQuestionBySurveyId(surveyId, userId);
    }


    /**
     * 计算答题占比 = 每个选项的人数 / 答题人数
     *
     * @param surveyId
     * @return
     */
    @Override
    public List<Question> querySurveyQuestionAnalysis(Long surveyId) {
        //查询问卷是否性格 | 人格问卷
        Survey survey = surveyService.getById(surveyId);
        String questionType = survey.getQuestionType();
        //已答题人列表 - 分母
        List<SurveyRecord> surveyRecordList = surveyRecordService.lambdaQuery().eq(SurveyRecord::getSurveyId, surveyId).eq(SurveyRecord::getRecordStatus, "Y").list();

        List<Question> questionList = baseMapper.selectList(Wrappers.lambdaQuery(Question.class).eq(Question::getSurveyId, surveyId).eq(Question::getDeleted, "0"));
        if (surveyRecordList.size() == 0 || questionList.size() == 0) {
            return questionList;
        }
        NumberFormat format = NumberFormat.getInstance();
        format.setMaximumFractionDigits(2);
        int recordSum = surveyRecordList.size();
        for (Question question : questionList) {
            if ("select".equals(question.getIsSelectPack())) {
                if (StringUtils.isNotEmpty(question.getOptionA())) {
                    List<Answer> list = answerService.selectAnswerCount("A", question.getQuestionId());
                    if (list.size() == 0) {
                        question.setRatioOptionA("0%");
                    } else {
                        int size = list.size();
                        String result = format.format((float) size / (float) recordSum * 100);
                        question.setRatioOptionA(result + "%");
                    }
                }
                if (StringUtils.isNotEmpty(question.getOptionB())) {
                    List<Answer> list = answerService.selectAnswerCount("B", question.getQuestionId());
                    if (list.size() == 0) {
                        question.setRatioOptionB("0%");
                    } else {
                        int size = list.size();
                        String result = format.format((float) size / (float) recordSum * 100);
                        question.setRatioOptionB(result + "%");
                    }
                }
                if (StringUtils.isNotEmpty(question.getOptionC())) {
                    List<Answer> list = answerService.selectAnswerCount("C", question.getQuestionId());
                    if (list.size() == 0) {
                        question.setRatioOptionC("0%");
                    } else {
                        int size = list.size();
                        String result = format.format((float) size / (float) recordSum * 100);
                        question.setRatioOptionC(result + "%");
                    }
                }
                if (StringUtils.isNotEmpty(question.getOptionD())) {
                    List<Answer> list = answerService.selectAnswerCount("D", question.getQuestionId());
                    if (list.size() == 0) {
                        question.setRatioOptionD("0%");
                    } else {
                        int size = list.size();
                        String result = format.format((float) size / (float) recordSum * 100);
                        question.setRatioOptionD(result + "%");
                    }
                }
                if (StringUtils.isNotEmpty(question.getOptionE())) {
                    List<Answer> list = answerService.selectAnswerCount("E", question.getQuestionId());
                    if (list.size() == 0) {
                        question.setRatioOptionE("0%");
                    } else {
                        int size = list.size();
                        String result = format.format((float) size / (float) recordSum * 100);
                        question.setRatioOptionE(result + "%");
                    }
                }
                if (StringUtils.isNotEmpty(question.getOptionF())) {
                    List<Answer> list = answerService.selectAnswerCount("F", question.getQuestionId());
                    if (list.size() == 0) {
                        question.setRatioOptionF("0%");
                    } else {
                        int size = list.size();
                        String result = format.format((float) size / (float) recordSum * 100);
                        question.setRatioOptionF(result + "%");
                    }
                }
                if (StringUtils.isNotEmpty(question.getOptionG())) {
                    List<Answer> list = answerService.selectAnswerCount("G", question.getQuestionId());
                    if (list.size() == 0) {
                        question.setRatioOptionG("0%");
                    } else {
                        int size = list.size();
                        String result = format.format((float) size / (float) recordSum * 100);
                        question.setRatioOptionG(result + "%");
                    }
                }
                List<Answer> answerList = answerService.selectAnswerListAndScore(question.getQuestionId());
                if (answerList.size() == 0) {
                    question.setAvgScore(0);
                    question.setAvgScoreUpCount(0);
                    question.setAvgScoreLowCount(0);
                    question.setAvgScoreLowRadio("0%");
                    question.setAvgScoreLowRadio("0%");
                    continue;
                }
                if (!"CHARACTER".equals(questionType)) {
                    Integer result = 0;
                    List<Integer> integerList = new ArrayList<>();

                    for (Answer answerItem : answerList) {
                        Integer resultOne = 0;
                        String answer = answerItem.getAnswer();
                        if (answer.contains("A")) {
                            result += answerItem.getScoreOptionA();
                            resultOne += answerItem.getScoreOptionA();
                        }
                        if (answer.contains("B")) {
                            result += answerItem.getScoreOptionB();
                            resultOne += answerItem.getScoreOptionB();
                        }
                        if (answer.contains("C")) {
                            result += answerItem.getScoreOptionC();
                            resultOne += answerItem.getScoreOptionC();
                        }
                        if (answer.contains("D")) {
                            result += answerItem.getScoreOptionD();
                            resultOne += answerItem.getScoreOptionD();
                        }
                        if (answer.contains("E")) {
                            result += answerItem.getScoreOptionE();
                            resultOne += answerItem.getScoreOptionE();
                        }
                        if (answer.contains("F")) {
                            result += answerItem.getScoreOptionF();
                            resultOne += answerItem.getScoreOptionF();
                        }
                        if (answer.contains("G")) {
                            result += answerItem.getScoreOptionG();
                            resultOne += answerItem.getScoreOptionG();
                        }
                        integerList.add(resultOne);
                    }
                    int size = answerList.size();
                    int avgScore = result / size;
                    question.setAvgScore(avgScore);
                    int countUp = (int) integerList.stream().filter(item -> {
                        return item > avgScore;
                    }).count();
                    int countLow = (int) integerList.stream().filter(item -> {
                        return item < avgScore;
                    }).count();
                    question.setAvgScoreUpCount(countUp);
                    question.setAvgScoreLowCount(countLow);
                    String avgScoreUpRadio = format.format((float) countUp / (float) size * 100);
                    String avgScoreLowRadio = format.format((float) countLow / (float) size * 100);
                    question.setAvgScoreUpRadio(avgScoreUpRadio + "%");
                    question.setAvgScoreLowRadio(avgScoreLowRadio + "%");
                } else {
                    question.setAvgScoreUpRadio(" 无");
                    question.setAvgScoreLowRadio(" 无");
                }
            }
        }
        return questionList;
    }


    @Override
    public List<Long> selectTikuIdBySurveyTemplateId(Long surveyId) {
        return baseMapper.selectTikuIdBySurveyTemplateId(surveyId);
    }

    @Override
    public List<Question> querySurveyBySurveyIdX(Long surveyId) {
        return baseMapper.querySurveyBySurveyIdX(surveyId);
    }
}